<template>
	<el-card>
		<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
			
			<el-form-item>
				<el-input v-model="state.queryForm.name" placeholder="名称" clearable></el-input>
			</el-form-item>
			
            <el-form-item>
                <vue-button button-text="查询" @emit-event="getDataList()" :button-opr="constant.ButtonTypeMap.SelectPagerKey"></vue-button>
            </el-form-item>

            <el-form-item>
                <vue-button  button-text="新增"  @emit-event="addOrUpdateHandle()" :button-opr="constant.ButtonTypeMap.AddKey"></vue-button>
            </el-form-item>

			<el-form-item>
            </el-form-item>

		</el-form>
		<el-table :v-loading="state.dataListLoading"
		:data="state.dataList" 
		border 
		style="width: 100%" 
		v-loading="loading"
		@selection-change="selectionChangeHandle"
		>
		    <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>

			<el-table-column prop="pipelineService" label="流水线名称" header-align="center" align="center">
				<template #default="scope">
					<el-button type="primary" link @click="viewDetails(scope.row)">
						{{ scope.row.pipelineName}}
					</el-button>
				</template>
			</el-table-column>

			<el-table-column prop="pipelineBranch" label="分支" header-align="center" align="center" ></el-table-column>

			<el-table-column label="操作人" prop="currentTaskOprName" />
			<el-table-column label="操作时间">
			
				<template #default="props">
				
				<span v-if="props.row.currentTaskRunningTime != null">
					{{dayjs(props.row.currentTaskRunningTime).format('YYYY-MM-DD HH:mm:ss')  }}
				</span>
				
				</template>
			</el-table-column>

			<el-table-column  label="状态" header-align="center" align="center">
				<template #default="scope">
					<div @mouseover="mouseover(scope.row)" @mouseout="mouseout(scope.row)" @click="cancelTask(scope.row)" style="cursor: pointer;">
						<el-button 
						style="width:80px ;"
						size="small"
						:type=getLodingType(scope.row) 
						:icon=getLodingImg(scope.row)
						:loading=getLoading(scope.row)
						>{{getLodingText(scope.row)}}
					</el-button>
					</div>
				</template>
			</el-table-column>

			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="180">

				<template #default="scope">
					<vue-button :button-link=true @emit-event="startPipeline(scope.row.id)" button-text="启动"></vue-button>
					<vue-button :button-link=true button-text="关闭"  @emit-event="addOrUpdateHandle()" :button-opr="constant.ButtonTypeMap.DeleteKey"></vue-button>

				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.page"
			:page-sizes="state.pageSizes"
			:page-size="state.limit"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>

		<!-- 弹窗, 新增 / 修改 -->
		<add-or-update ref="addOrUpdateRef" @refreshDataList="getDataList"></add-or-update>
		
		<!-- 详情 -->
		<task-details ref="taskDetails"></task-details>
	</el-card>

</template>

<script setup lang="ts">
import { useCrud } from '@/hooks'
import { reactive, ref ,onMounted,onBeforeUnmount} from 'vue'
import { PagerOptions } from '@/hooks/pager'
import constant from '@/utils/constant'
import AddOrUpdate from './add-or-update.vue'
import { useRoute } from 'vue-router'
import { getRequest, postReq} from '@/utils/request'
import uri from '@/api/uri'
import { ElMessage} from 'element-plus/es'
import TaskDetails from './task-details.vue'
import dayjs from 'dayjs'

import { Eleme,CircleCloseFilled,SuccessFilled } from '@element-plus/icons-vue'

const route = useRoute()

const state: PagerOptions = reactive({
    dataListUrl: route.path,
    deleteIsNeed:false,
	queryForm: {
		pipelineName: ''
	}
})

const loading = ref(false)
const addOrUpdateRef = ref()
const taskDetails = ref()

const addOrUpdateHandle = (id?: number) => {
	addOrUpdateRef.value.init(id)
}

let timerId = ref(-1)

const viewDetails = (pipelineInfo:any) =>{
	taskDetails.value.init(pipelineInfo)
}

const startPipeline =(id:any) =>{
	loading.value = true
	getRequest(uri.startPipeline,{"id":id}).then(res =>{
		loading.value = false
		ElMessage.success({
			message: '操作成功',
			duration: 500,
		})
		getDataList()
	})
	
	setTimeout(() => { 
		loading.value = false
		getDataList()
	}, 5000)
}

//按钮文本
const getLodingText =(row: any) =>{
	
	if(!row || !row.pipelineStatus){
		return "无任务"
	}

	if((row.status == 1 || row.status == 2)  && row.mouseHover){
		return "终止"
	}

	return row.pipelineStatus
}

//按钮类型
const getLodingType =(row: any) =>{
	
	if(!row){
		return "primary"
	}

	if(row.status == 1 || row.status == 2){
		if(row.mouseHover){
			return "danger"
		}
		return "primary"
	}

	if(row.status == 3){
		return "success"
	}

	if(row.status == -1 || row.status == 4 || row.status == 5 ){
		return "danger"
	}
	return "primary"
}

//按钮图标
const getLodingImg =(row: any) =>{
	
	if(!row){
		return Eleme
	}

	if(row.status  == 1 || row.status  == 2){
	
		if(row.mouseHover){
			return CircleCloseFilled
		}

		return Eleme
	}

	if(row.status  == 3){
		return SuccessFilled
	}

	if(row.status  == -1 || row.status == 4 || row.status == 5){
		return CircleCloseFilled
	}

	return Eleme
}

//是否加载中
const getLoading =(row:any) =>{
	if(!row){
		return false
	}
	if(row.status  == 2){
		return true
	}
	return false
}



const mouseover = (row: any) =>{
	
	if(!row){
		return 
	}
	row.mouseHover = true
}

const mouseout = (row: any) =>{

	if(!row){
		return 
	}
	 row.mouseHover = false
}

//取消任务
const cancelTask = (row:any) => {

	if(row.status != 2) return
	loading.value = true
	getRequest(uri.stopPipeline,{"pipelineId":row.id}).then(res =>{
		ElMessage.success({
			message: '操作成功',
			duration: 500,
		})
		loading.value = false
		getDataList()
	})

}



const getPipelineStatus = () =>{
	let idArr = state.dataList?.map(item => {
		return item.id
	})
	if(!idArr || idArr.length <= 0){
		return
	}
	
	const taskIdList = taskDetails.value.getNeedUpdateTask()
	postReq(uri.getPipelineStatus,{"pipelineIdList":idArr,"taskIdList":taskIdList}).then(res =>{
		console.info("主页面请求流水线状态返回结果:",res.data)
		state.dataList?.forEach(item =>{
			if(res.data[item.id]){
				item.status = res.data[item.id].status
				item.pipelineStatus = res.data[item.id].pipelineStatus
				const taskStatMap = res.data[item.id].taskStatMap
				if(taskStatMap && Object.keys(taskStatMap).length != 0){
					//更新子模块的任务状态
					taskDetails.value.updateTaskStatus(taskStatMap)
        		}
			}
		})
		
		
	})
}




onMounted(() =>{
	//startInterval()
})


onBeforeUnmount(() => {  
	stopInterval()
}); 


const stopInterval = () => {
	console.info("关闭主页面获取流水线状态的定时任务")
	clearTimeout(timerId.value)
}

const startInterval = () =>{
	if(timerId.value){
		stopInterval()
	}
	console.info("开启主页面获取流水线状态的定时任务")
	timerId.value = setInterval(getPipelineStatus,25000);
}


const { getDataList, selectionChangeHandle, sizeChangeHandle, currentChangeHandle } = useCrud(state)
</script>
